<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryRef"
      :inline="true"
      v-show="showSearch"
      label-width="90px"
    >
      <!-- <SearchTool
        :layout="false"
        v-model:factory="queryParams.factoryCode"
        v-model:workshop="queryParams.segment"
        v-model:line="queryParams.productionLine"
        v-model:section="queryParams.processSegment"
      ></SearchTool> -->
      <el-form-item label="工厂" prop="factory">
        <el-select
          v-model="queryParams.factory"
          placeholder="请选择"
          style="width: 220px"
          clearable
          filterable
          @change="handleSearchListChange('factory')"
        >
          <el-option
            v-for="(item, index) in factoryOptions"
            :key="index"
            :label="item.deptName"
            :value="item.deptCode"
          >
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="工段名称" prop="workshopCode">
        <el-select
          v-model="queryParams.workshopCode"
          placeholder="请选择"
          clearable
          filterable
          style="width: 220px"
          @change="handleSearchListChange('workshopCode')"
        >
          <el-option
            v-for="(item, index) in workshopOptions"
            :key="index"
            :label="item.deptName"
            :value="item.deptCode"
          >
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="产线名称" prop="productLine">
        <el-select
          v-model="queryParams.productLine"
          placeholder="请选择"
          clearable
          filterable
          style="width: 220px"
          @change="handleSearchListChange('productLine')"
        >
          <el-option
            v-for="(item, index) in lineOptions"
            :key="index"
            :label="item.deptName"
            :value="item.deptCode"
          >
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="工艺段名称" prop="sectionCode">
        <el-select
          v-model="queryParams.sectionCode"
          placeholder="请选择"
          clearable
          filterable
          style="width: 220px"
          @change="handleSearchListChange('sectionCode')"
        >
          <el-option
            v-for="(item, index) in processOptions"
            :key="index"
            :label="item.deptName"
            :value="item.deptCode"
          >
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="计划名称" prop="planName">
        <el-input
          v-model="queryParams.planName"
          placeholder="请输入计划名称"
          clearable
          style="width: 220px"
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="日期" prop="date">
        <el-date-picker
          v-model="queryParams.date"
          type="daterange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          style="width: 220px"
          value-format="YYYY-MM-DD"
        >
        </el-date-picker>
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select
          v-model="queryParams.status"
          placeholder="请选择状态"
          clearable
          filterable
          style="width: 220px"
        >
          <el-option
            v-for="(item, index) in statusList"
            :key="index"
            :label="item.label"
            :value="item.value"
          >
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['planning:planSchedule:add']"
          >新增</el-button
        >
      </el-col>
      <!-- <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Edit"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['planning:planSchedule:edit']"
          >编辑</el-button
        >
      </el-col> -->
      <!-- <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['planning:planSchedule:remove']"
          >删除</el-button
        >
      </el-col> -->
      <right-toolbar
        v-model:showSearch="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>

    <el-table
      v-loading="loading"
      :data="typeList"
      border
      max-height="500"
      @selection-change="handleSelectionChange"
    >
      <!-- <el-table-column type="selection" width="55" align="center" /> -->
      <!-- <el-table-column label="计划编号" align="center" prop="planCode" /> -->
      <el-table-column
        label="计划编号"
        prop="planCode"
        :show-overflow-tooltip="true"
        align="center"
        width="120"
      >
        <template #default="scope">
          <el-link type="primary" @click="handleDetail(scope.row)">{{
            scope.row.planCode
          }}</el-link>
        </template>
      </el-table-column>
      <el-table-column label="计划名称" align="center" prop="planName" />
      <el-table-column label="工厂" align="center" prop="factoryName" />
      <el-table-column label="工段" align="center" prop="workshopName" />
      <el-table-column label="产线" align="center" prop="productLineName" />
      <el-table-column label="工艺段" align="center" prop="sectionName" />
      <el-table-column label="开始日期" prop="startDate">
        <template #default="scope">
          <span>{{ scope.row.startDate }}</span>
        </template>
      </el-table-column>
      <el-table-column label="结束日期" prop="endDate">
        <template #default="scope">
          <span>{{ scope.row.endDate }}</span>
        </template>
      </el-table-column>
      <el-table-column label="轮班方式" prop="classesMode">
        <template #default="scope">
          <span v-if="scope.row.classesMode == 1">一班</span>
          <span v-if="scope.row.classesMode == 2">两班倒</span>
          <span v-if="scope.row.classesMode == 3">三班倒</span>
        </template>
      </el-table-column>
      <el-table-column label="倒班方式" prop="changeShiftsMode">
        <template #default="scope">
          <span v-if="scope.row.changeShiftsMode == 1"
            >每{{ scope.row.cycle }}周</span
          >
          <span v-if="scope.row.changeShiftsMode == 2"
            >每{{ scope.row.cycle }}天</span
          >
          <span v-if="scope.row.changeShiftsMode == 3"
            >每{{ scope.row.cycle }}月</span
          >
        </template>
      </el-table-column>
      <!-- <el-table-column
        label="倒班方式"
        align="center"
        prop="changeShiftsMode"
      /> -->
      <el-table-column label="班组" prop="scheduleGroupName" />
      <el-table-column label="启用时间" prop="enableTime">
        <template #default="scope">
          <span>{{ scope.row.enableTime }}</span>
        </template>
      </el-table-column>
      <el-table-column label="状态" prop="status"
        ><template #default="scope">
          <span v-if="scope.row.status == '0'">待启用</span>
          <span v-if="scope.row.status == '1'">已启用</span>
        </template>
      </el-table-column>
      <el-table-column
        label="操作"
        align="center"
        width="160"
        class-name="small-padding fixed-width"
      >
        <template #default="scope">
          <el-button
            link
            type="primary"
            icon="Edit"
            v-hasPermi="['planning:planSchedule:enable']"
            @click="handleEnable(scope.row)"
            v-if="scope.row.status == '0'"
            >启用</el-button
          >
          <el-button
            link
            type="primary"
            icon="Edit"
            v-hasPermi="['planning:planSchedule:edit']"
            @click="handleUpdate(scope.row)"
            v-if="scope.row.status == '0'"
            >编辑</el-button
          >
          <el-button
            link
            type="primary"
            icon="Delete"
            v-hasPermi="['planning:planSchedule:remove']"
            @click="handleDelete(scope.row)"
            v-if="scope.row.status == '0'"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改参数配置对话框 -->
    <el-dialog
      :title="title"
      :close-on-click-modal="false"
      v-model="open"
      width="800px"
      append-to-body
    >
      <el-form
        ref="formRef"
        :inline="true"
        :model="form"
        :rules="rules"
        label-width="80px"
      >
        <el-form-item label="计划编号" prop="planCode">
          <code-input
            v-model="form.planCode"
            code="PLAN_CODE"
            :disabled="!!form.id"
            placeholder="请输入计划编号"
            style="width: 220px"
          />
        </el-form-item>
        <el-form-item label="计划名称" prop="planName">
          <el-input
            v-model="form.planName"
            placeholder="请输入计划名称"
            style="width: 220px"
          />
        </el-form-item>
        <el-form-item label="工厂" prop="factory">
          <el-select
            v-model="form.factory"
            placeholder="请选择"
            clearable
            filterable
            style="width: 220px"
            @change="handleSearchFormChange('factory')"
          >
            <el-option
              v-for="(item, index) in factoryOptions"
              :key="index"
              :label="item.deptName"
              :value="item.deptCode"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="工段" prop="workshopCode">
          <el-select
            v-model="form.workshopCode"
            placeholder="请选择"
            clearable
            filterable
            style="width: 220px"
            @change="handleSearchFormChange('workshopCode')"
          >
            <el-option
              v-for="(item, index) in workshopOptions"
              :key="index"
              :label="item.deptName"
              :value="item.deptCode"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="产线" prop="productLine">
          <el-select
            v-model="form.productLine"
            placeholder="请选择"
            style="width: 220px"
            clearable
            filterable
            @change="handleSearchFormChange('productLine')"
          >
            <el-option
              v-for="(item, index) in lineOptions"
              :key="index"
              :label="item.deptName"
              :value="item.deptCode"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="工艺段" prop="sectionCode">
          <el-select
            v-model="form.sectionCode"
            placeholder="请选择"
            style="width: 220px"
            clearable
            filterable
            @change="sectionChange"
          >
            <el-option
              v-for="(item, index) in processOptions"
              :key="index"
              :label="item.deptName"
              :value="item.deptCode"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="开始日期" prop="startDate">
          <el-date-picker
            v-model="form.startDate"
            type="date"
            placeholder="选择开始日期"
            style="width: 220px"
            value-format="YYYY-MM-DD"
            :editable="false"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item label="结束日期" prop="endDate">
          <el-date-picker
            v-model="form.endDate"
            type="date"
            placeholder="选择结束日期"
            style="width: 220px"
            :editable="false"
            value-format="YYYY-MM-DD"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item label="轮班方式" prop="classesMode">
          <el-radio-group
            v-model="form.classesMode"
            @change="modeChange"
            style="width: 220px"
          >
            <el-radio
              v-for="dict in shift_mode_show"
              :key="dict.value"
              :value="dict.value"
              >{{ dict.label }}</el-radio
            >
          </el-radio-group>
        </el-form-item>
        <el-form-item label="倒班方式" prop="changeShiftsMode">
          <el-select
            v-model="form.changeShiftsMode"
            placeholder="请选择"
            clearable
            filterable
            style="width: 100px"
          >
            <el-option
              v-for="(item, index) in shiftFrequency"
              :key="index"
              :label="item.label"
              :value="item.value"
            >
            </el-option>
          </el-select>
          <el-input-number
            v-model="form.cycle"
            :min="1"
            :max="1000"
            style="width: 140px"
          ></el-input-number>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input
            v-model="form.remark"
            type="textarea"
            placeholder="请输入内容"
            style="width: 580px"
            maxlength="200"
            :rows="3"
            show-word-limit
          ></el-input>
        </el-form-item>
        <div
          style="
            width: 100%;
            height: 1px;
            background-color: #ccc;
            margin-bottom: 15px;
          "
        ></div>
        <el-form-item label="班次" prop="classesCode">
          <el-select
            v-model="form.classesCode"
            placeholder="请选择"
            style="width: 220px"
            clearable
            filterable
            @change="shiftClassesChange"
          >
            <el-option
              v-for="(item, index) in shiftGroupsList"
              :key="index"
              :label="item.classesName"
              :value="item.classesCode"
            >
            </el-option>
          </el-select>
          <el-table
            :data="tableData"
            border
            style="width: 100%; margin-top: 10px"
          >
            <el-table-column prop="scheduleName" label="班次" width="">
            </el-table-column>
            <el-table-column prop="startTime" label="开始时间" width="">
            </el-table-column>
            <el-table-column prop="endTime" label="结束时间"> </el-table-column>
          </el-table>
        </el-form-item>
        <el-form-item label="班组" prop="planScheduleGroupList">
          <el-select
            v-model="form.planScheduleGroupList"
            placeholder="请选择"
            style="width: 220px"
            multiple
            clearable
            @change="handlePlanGroup"
          >
            <el-option
              v-for="(item, index) in planGroupList"
              :key="index"
              :label="item.workGroupName"
              :value="item.workGroup"
            >
            </el-option>
          </el-select>
          <el-table
            :data="planGroupTableList"
            border
            style="width: 100%; margin-top: 10px"
          >
            <el-table-column prop="workGroupName" label="班组" width="" />
            <el-table-column prop="monitorName" label="班长" width="" />
            <el-table-column prop="groupMemberName" label="班组成员" width="" />
            <el-table-column label="排班顺序" prop=""
              ><template #default="scope">
                <span>{{ scope.$index + 1 }}</span>
              </template>
            </el-table-column>
            <!-- <el-table-column prop="" label="操作" width="" /> -->
            <el-table-column label="操作">
              <template #default="scope">
                <el-button
                  v-if="scope.$index != 0"
                  link
                  type="primary"
                  icon="Edit"
                  @click="handleItemsUp(scope.row, scope.$index)"
                  >上移</el-button
                >
                <el-button
                  v-if="
                    scope.row.id !=
                    planGroupTableList[planGroupTableList.length - 1].id
                  "
                  link
                  type="primary"
                  icon="Edit"
                  @click="handleItemsDown(scope.row, scope.$index)"
                  >下移</el-button
                >
              </template>
            </el-table-column>
          </el-table>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
    <el-dialog
    v-model="dialogVisible"
    title="系统提示"
    width="500px"
  >
    <span>{{ enbelTips }}</span>
    <p style="color: red;">若排班计划出现冲突，则以最新启用的计划为准，启用后可在【排班日历】中查看排班结果。</p>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="sureEnbel">
          确定
        </el-button>
      </div>
    </template>
  </el-dialog>
  </div>
</template>

<script setup name="ShiftMaintenance">
import SearchTool from "@/components/SearchTool";
import {
  listShiftSchedule,
  getShiftSchedule,
  delShiftSchedule,
  addShiftSchedule,
  updateShiftSchedule,
  planEnable,
} from "@/api/base/plan/shiftMgt/shiftPlan";
import { listShift } from "@/api/base/plan/shiftMgt/shiftMaintenance";
import { listShiftGroup } from "@/api/base/plan/shiftMgt/shiftGroup";
import { getFactoryTree, depeIdSelectList } from "@/api/system/dept";
import { SHIFT_MODE, SHIFT_FREQUENCY } from "../config";
import DetailData from "./data";

const { proxy } = getCurrentInstance();
const { shift_mode } = proxy.useDict("shift_mode");
const shift_mode_show = ref([
  {
    value: 2,
    label: "两班倒",
  },
]);

const typeList = ref([
  {
    id: 1,
    planCode: "CS001",
  },
]);
const tableData = ref([]);
const shiftGroupsList = ref([]);
const planGroupList = ref([]);
const planGroupTableList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const dateRange = ref([]);
const dialogVisible = ref(false)
const enbelTips = ref('')
const enabelIds = ref('')
const statusList = ref([
  {
    label: "待启用",
    value: "0",
  },
  {
    label: "已启用",
    value: "1",
  },
]);
var factoryOptions = ref([]);
var workshopOptions = ref([]);
var lineOptions = ref([]);
var processOptions = ref([]);

const data = reactive({
  form: {
    cycle: 1,
  },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    // cycle: 1,
    name: undefined,
  },
  rules: {
    planCode: [
      { required: true, message: "计划编号不能为空", trigger: "blur" },
    ],
    planName: [
      { required: true, message: "计划名称不能为空", trigger: "blur" },
    ],
    factory: [
      { required: true, message: "工厂不能为空", trigger: "change" },
    ],
    workshopCode: [
      { required: true, message: "工段不能为空", trigger: "change" },
    ],
    productLine: [
      { required: true, message: "产线不能为空", trigger: "change" },
    ],
    sectionCode: [
      { required: true, message: "工艺段不能为空", trigger: "change" },
    ],
    startDate: [
      { required: true, message: "开始日期不能为空", trigger: "change" },
    ],
    endDate: [
      { required: true, message: "结束日期不能为空", trigger: "change" },
    ],
    changeShiftsMode: [
      { required: true, message: "倒班方式不能为空", trigger: "change" },
    ],
    classesCode: [
      { required: true, message: "班次不能为空", trigger: "change" },
    ],
    classesCode: [
      { required: true, message: "班次不能为空", trigger: "change" },
    ],
    planScheduleGroupList: [
      { required: true, message: "班组不能为空", trigger: "change" },
    ],
  },
});

const { queryParams, form, rules } = toRefs(data);
const shiftMode = SHIFT_MODE;
const shiftFrequency = SHIFT_FREQUENCY;
/** 查询设备类型列表 */
function getList() {
  loading.value = true;
  let newForm = JSON.parse(JSON.stringify(queryParams.value));
  if (queryParams.value?.date?.length) {
    newForm.startDate = queryParams.value.date[0];
    newForm.endDate = queryParams.value.date[1];
    delete newForm.date;
  }
  listShiftSchedule(proxy.addDateRange(newForm)).then((response) => {
    typeList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

function getFactorys(query) {
  getFactoryTree(query).then((res) => {
    factoryOptions.value = res.data;
  });
}

function handleSearchListChange(type) {
  if (type == "factory") {
    depeIdSelectList({
      deptType: "station",
      deptCode: queryParams.value.factory,
    }).then((res) => {
      workshopOptions.value = res.data;
      lineOptions.value = [];
      processOptions.value = [];
      queryParams.value.workshopCode = "";
      queryParams.value.productLine = "";
      queryParams.value.sectionCode = "";
    });
  }
  if (type == "workshopCode") {
    depeIdSelectList({
      deptType: "line",
      deptCode: queryParams.value.workshopCode,
    }).then((res) => {
      lineOptions.value = res.data;
      processOptions.value = [];
      queryParams.value.productLine = "";
      queryParams.value.sectionCode = "";
    });
  }
  if (type == "productLine") {
    depeIdSelectList({
      deptType: "craft",
      deptCode: queryParams.value.productLine,
    }).then((res) => {
      processOptions.value = res.data;
      queryParams.value.sectionCode = "";
    });
  }
}

function handleSearchFormChange(type) {
  if (type == "factory") {
    // 根据工厂带出轮班方式
    form.value.classesMode =
      factoryOptions.value.find((item) => item.deptCode == form.value.factory)
        ?.classesMode || "2";
    // 轮班方式
    shift_mode_show.value = shift_mode.value.filter((item) => {
      return item.value == form.value.classesMode;
    });
    // 根据轮班方式带出班次
    modeChange(form.value.classesMode);

    // 清空班组与列表
    form.value.planScheduleGroupList = [];
    // 班组table列表置空
    planGroupTableList.value = [];
    // 班组选项列表置空planGroupList
    planGroupList.value = [];
    // 工段以下列表清空
    workshopOptions.value = [];
    lineOptions.value = [];
    processOptions.value = [];
    form.value.workshopCode = "";
    form.value.productLine = "";
    form.value.sectionCode = "";
    if (form.value.factory) {
      // 获取工段
      depeIdSelectList({
        deptType: "station",
        deptCode: form.value.factory,
      }).then((res) => {
        workshopOptions.value = res.data;
        lineOptions.value = [];
        processOptions.value = [];
        form.value.workshopCode = "";
        form.value.productLine = "";
        form.value.sectionCode = "";
      });
    }
  }
  if (type == "workshopCode") {
    // 清空班组与列表
    form.value.planScheduleGroupList = [];
    // 班组table列表置空
    planGroupTableList.value = [];
    // 班组选项列表置空planGroupList
    planGroupList.value = [];
    // 工段以下列表清空
    lineOptions.value = [];
    processOptions.value = [];
    form.value.productLine = "";
    form.value.sectionCode = "";

    // 产线、工艺段选项置空
    processOptions.value = [];
    if (form.value.workshopCode) {
      depeIdSelectList({
        deptType: "line",
        deptCode: form.value.workshopCode,
      }).then((res) => {
        lineOptions.value = res.data;
        processOptions.value = [];
        form.value.productLine = "";
        form.value.sectionCode = "";
      });
    }
  }
  if (type == "productLine") {
    // 清空班组与列表
    form.value.planScheduleGroupList = [];
    // 班组table列表置空
    planGroupTableList.value = [];
    // 班组选项列表置空planGroupList
    planGroupList.value = [];
    // 产线、工艺段选项置空
    form.value.sectionCode = "";
    processOptions.value = [];
    if (form.value.productLine) {
      depeIdSelectList({
        deptType: "craft",
        deptCode: form.value.productLine,
      }).then((res) => {
        processOptions.value = res.data;
        form.value.sectionCode = "";
      });
    }
  }
}

/** 取消按钮 */
function cancel() {
  open.value = false;
  reset();
}

function handleDetail(row) {
  proxy.subPage(DetailData, { title: "排班计划详情", data: row });
}

/** 表单重置 */
function reset() {
  form.value = {
    classesCode: "",
    classesName: "",
    classesMode: "",
    planScheduleGroupList: [],
    planClassesScheduleList: [],
    remark: "",
  };
  planGroupTableList.value = [];
  proxy.resetForm("formRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  dateRange.value = [];
  proxy.resetForm("queryRef");
  handleQuery();
}

function modeChange(value) {
  getListShift(value);
}

function getListShift(classesMode) {
  listShift().then((res) => {
    if (res.code == 200) {
      shiftGroupsList.value = res?.rows || [];
      let _datas = res.rows.find((item) => {
        return item.classesMode == classesMode;
      });
      let datasArr = res.rows.filter((item) => {
        return item.classesMode == classesMode;
      });
      shiftGroupsList.value = datasArr||res?.rows;
      form.value.classesCode =
        _datas?.classesCode || res.rows[0]?.classesCode || "";
      tableData.value =
        _datas?.planClassesScheduleList ||
        res.rows[0]?.planClassesScheduleList ||
        [];
    }
  });
}

function getListShiftGroup() {
  listShiftGroup({
    sectionCode: form.value.sectionCode,
    pageNum: 1,
    pageSize: 999,
  }).then((response) => {
    planGroupList.value = response?.rows || [];
  });
}

function sectionChange() {
  console.log("sasaaas", form.value.sectionCode);
  // 清空班组与列表
  form.value.planScheduleGroupList = [];
  // 班组table列表置空
  planGroupTableList.value = [];
  // 班组选项列表置空planGroupList
  planGroupList.value = [];
  if (form.value.sectionCode) {
    getListShiftGroup();
  }
}

function shiftClassesChange() {
  let _data =
    shiftGroupsList.value.find((item) => {
      return item.classesCode == form.value.classesCode;
    })?.planClassesScheduleList || [];
  tableData.value = _data || [];
}
function handlePlanGroup() {
  let _data = [];
  for (let i in form.value.planScheduleGroupList) {
    let _items = form.value.planScheduleGroupList[i];
    for (let j in planGroupList.value) {
      if (_items == planGroupList.value[j].workGroup) {
        _data.push({ ...planGroupList.value[j] });
      }
    }
  }
  planGroupTableList.value = _data || [];
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加排班计划";
  // getListShift();
  // 倒班方式默认值
  form.value.changeShiftsMode = "1";
  form.value.cycle = 1;
  form.value.classesMode = 2;
}

/** 多选框选中数据 */
function handleSelectionChange(selection) {
  ids.value = selection.map((item) => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const typeId = row.id;
  getShiftSchedule(typeId).then((response) => {
    form.value = JSON.parse(JSON.stringify(response.data));
    open.value = true;
    title.value = "编辑排班计划";
    // 工厂、工段、产线、工艺段
    if (form.value.factory) {
      depeIdSelectList({
        deptType: "station",
        deptCode: form.value.factory,
      }).then((res) => {
        workshopOptions.value = res.data;
      });
    }
    if (form.value.workshopCode) {
      depeIdSelectList({
        deptType: "line",
        deptCode: form.value.workshopCode,
      }).then((res) => {
        lineOptions.value = res.data;
      });
    }
    if (form.value.productLine) {
      depeIdSelectList({
        deptType: "craft",
        deptCode: form.value.productLine,
      }).then((res) => {
        processOptions.value = res.data;
      });
    }
    if (form.value.sectionCode) {
      getListShiftGroup();
    }
    // 轮班方式
    shift_mode_show.value = shift_mode.value.filter((item) => {
      return item.value == form.value.classesMode;
    });
    // 班次
    getListShift(form.value.classesMode);
    // 班组
    form.value.planScheduleGroupList =
      response.data?.planScheduleGroupList.map((item) => item.workGroup) || [];
    // 班组tablel列表
    planGroupTableList.value =
      response.data?.planScheduleGroupList.map((item) => {
        return {
          ...item,
          monitorName: item.monitor,
          groupMemberName: item.workStationStaff,
        };
      }) || [];
  });
}

function handleItemsDown(row, index) {
  if (index < planGroupTableList.value.length - 1) {
    const temp = planGroupTableList.value[index];
    planGroupTableList.value[index] = planGroupTableList.value[index + 1];
    planGroupTableList.value[index + 1] = temp;
  }
}

function handleItemsUp(row, index) {
  if (index > 0) {
    const item = planGroupTableList.value.splice(index, 1)[0];
    planGroupTableList.value.splice(index - 1, 0, item);
  }
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["formRef"].validate((valid) => {
    if (valid) {
      let dateFlag =
        new Date(form.value.endDate).getTime() -
        new Date(form.value.startDate).getTime();
      if (dateFlag < 0) {
        proxy.$modal.msgError("开始时间需小于结束时间！");
        return false;
      }
      let newForm = JSON.parse(JSON.stringify(form.value));
      newForm.factoryName =
        factoryOptions.value.find((item) => {
          return item.deptCode == form.value.factory;
        })?.deptName || "";
      newForm.workshopName =
        workshopOptions.value.find((item) => {
          return item.deptCode == form.value.workshopCode;
        })?.deptName || "";
      newForm.productLineName =
        lineOptions.value.find((item) => {
          return item.deptCode == form.value.productLine;
        })?.deptName || "";
      newForm.sectionName =
        processOptions.value.find((item) => {
          return item.deptCode == form.value.sectionCode;
        })?.deptName || "";
      let newArr = planGroupTableList.value.map((item, index) => {
        return {
          ...item,
          planCode: form.value.planCode,
          sort: Number(index) + 1,
          workStationStaff: item.planGroupMemberList,
          id: null,
        };
      });
      newForm.planScheduleGroupList = newArr || [];
      if (newForm.id != undefined) {
        updateShiftSchedule(newForm).then((response) => {
          proxy.$modal.msgSuccess("编辑成功");
          open.value = false;
          getList();
        });
      } else {
        addShiftSchedule(newForm).then((response) => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

function handleEnable(row) {
  const ids = row.id;
  enabelIds.value = ids
  dialogVisible.value = true
  enbelTips.value = '确定启用"' + row.planName + '"吗？'
  // proxy.$modal
  //   .confirm('确定启用"' + row.planName + '"吗？')
  //   .then(function () {
  //     return planEnable({ id: ids });
  //   })
  //   .then(() => {
  //     getList();
  //     proxy.$modal.msgSuccess("启用成功");
  //   })
  //   .catch(() => {});
}
function sureEnbel(){
  planEnable({ id: enabelIds.value }).then(() => {
    getList();
    dialogVisible.value = false
    proxy.$modal.msgSuccess("启用成功");
  });
}
/** 删除按钮操作 */
function handleDelete(row) {
  const planCode = row.planCode;
  const ids = row.id;
  proxy.$modal
    .confirm('是否确认删除计划编号为"' + planCode + '"的数据项？')
    .then(function () {
      return delShiftSchedule(ids);
    })
    .then(() => {
      getList();
      proxy.$modal.msgSuccess("删除成功");
    })
    .catch(() => {});
}

getList();
getFactorys();
</script>
